<!--  -->
<template>
  <div class="main">
    <h2>机构分类管理</h2>
    <el-button type="primary" style="margin:20px" @click="handleOpen('添加分类',1)">添加分类</el-button>

    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          align="center"
          prop="id"
          label="编号"
          min-width="10%"
        />

        <el-table-column
          align="center"
          prop="typeName"
          label="分类名称"
          min-width="20%"
        />

        <el-table-column
          align="center"
          prop="typeImg"
          label="分类图标"
          min-width="20%"
        >
          <template slot-scope="Scope">
            <img :src="Scope.row.typeImg" width="30px" height="30px">
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="order"
          label="分类排序"
          min-width="10%"
        />

        <el-table-column
          align="center"
          prop="typeState"
          label="分类状态"
          min-width="15%"
        >
          <template slot-scope="Scope">
            <span v-if="Scope.row.typeState==0">已关闭</span>
            <span v-if="Scope.row.typeState==1">已启用</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" min-width="25%">
          <template slot-scope="Scope">
            <el-button type="primary" icon="el-icon-edit" @click="handleOpen('修改分类',2,Scope.row.id)">修改分类</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleDelete(Scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5,10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="editVisiable" :before-close="handleClose">
      <el-form ref="classType" :model="classType" label-position="top" :rules="rules">
        <!-- <el-form-item label="编号">
          <el-input v-model="classType.id" autocomplete="off" readonly="" placeholder="无需填写" />
        </el-form-item> -->

        <el-form-item prop="typeName" label="分类名称" required="">
          <el-input
            v-model="classType.typeName"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="分类图标">
          <el-upload
            class="avatar-uploader"
            name="files"
            :action="url"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB,建议上传100*100的图片</div>
          </el-upload>
          <!-- <img v-if="editType==2" :src="classType.typeImg" width="200px" height="120px"> -->
        </el-form-item>

        <el-form-item label="分类排序">
          <el-input v-model="classType.order" autocomplete="off" type="number" />
        </el-form-item>

        <el-form-item label="状态：">
          <el-select v-model="classType.typeState" placeholder="请选择">
            <el-option key="0" label="已关闭" value="0" />
            <el-option key="1" label="已启用" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="editType==2" type="primary" @click="handleUpdate('classType')">修 改</el-button>
        <el-button v-if="editType==1" type="primary" @click="handleAdd('classType')">添 加</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { getAll, updateNameAndStateById, getClassTypeById, add, update, deleteById } from '@/api/classType'
export default {
  name: 'ClassType',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      list: [],
      imageUrl: '',
      listLoading: false,
      editVisiable: false,
      classType: {
        id: '',
        typeName: '',
        typeImg: '',
        typeState: '0',
        order: ''
      },
      editType: 1, // 1 添加 2 修改
      url: process.env.VUE_APP_BASE_API + 'file/',
      rules: {
        typeName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }, { validator: this.validateCharacter, trigger: ['blur', 'change'] }]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.fetchData()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.obj.split(';')[0]
      this.classType.typeImg = this.imageUrl
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isImage = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
      // return true
    },
    fetchData() {
      getAll().then((resp) => {
        this.list = resp.obj
      })
    },
    update(name, state, id) {
      updateNameAndStateById(id, name, state).then((resp) => {
        this.$notify({
          title: '操作成功',
          type: 'success'
        })
      })
    },
    handleOpen(title, type, id) {
      this.title = title
      this.editType = type
      this.editVisiable = true
      if (type === 2) {
        getClassTypeById(id).then((resp) => {
          this.classType = resp.obj
          this.imageUrl = resp.obj.typeImg
          this.classType.typeState = String(this.classType.typeState)
        })
      }
    },
    handleAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          add(this.classType.typeName, this.classType.typeImg, this.classType.typeState, this.classType.order).then((resp) => {
            this.$notify({
              title: '添加成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.editVisiable = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          update(this.classType.id, this.classType.typeName, this.classType.typeImg, this.classType.typeState, this.classType.order).then((resp) => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.editVisiable = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleDelete(id) {
      this.$confirm('确认删除？').then(() => {
        deleteById(id).then((resp) => {
          this.$notify({
            title: '删除成功',
            type: 'success'
          })
          const totalPage = Math.ceil((this.list.length - 1) / this.pagesize)
          const page = this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      })
    },
    handleClose() {
      this.editVisiable = false
      this.classType = {}
      this.imageUrl = ''
    },
    // 特殊字符过滤
    checkSpecificKey(str) {
      var specialKey = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'"
      for (var i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) !== -1) {
          return false
        }
      }
      return true
    },

    // 验证字符串
    validateFontSize(rule, value, callback) {
      if (value.length < 30) {
        callback()
      } else {
        callback(new Error('字符串长度在1-30之间'))
      }
    },

    // 验证字符串
    validateCharacter(rule, value, callback) {
      if (this.checkSpecificKey(value)) {
        callback()
      } else {
        callback(new Error('请不要输入特殊字符'))
      }
    }
  }
}
</script>
<style  scoped>
    #main{
        margin-left: 5px;
        margin-right: 5px;
    }

    #table-area{

        margin-left: 10px;
        margin-right: 10px;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 60px;
      height: 60px;
      line-height: 60px;
      text-align: center;
    }
    .avatar {
      width: 60px;
      height: 60px;
      display: block;
    }
</style>
